<?php
namespace api\modules\v1\models\transfer;

use api\modules\v1\models\Common;
use api\modules\v1\models\friend\Friend;
use api\modules\v1\models\group\GroupUser;
use api\modules\v1\models\user\User;
use common\models\CacheKeys;
use common\models\Functions;
use common\models\im\Im;
use common\models\Status;
use common\models\user\UserUnusualLog;
use common\models\userFund\UserMoneyLog;
use Yii;
use yii\base\Exception;
use yii\helpers\ArrayHelper;

/**
 * This is the model class for table "goods".
 *
 * @property int $id
 * @property string $name
 */
class Transfer extends \common\models\transfer\Transfer
{

    private $redis;
    public function __construct(array $config = [])
    {
        $this->redis = Yii::$app->redis;
        parent::__construct($config);
    }

    /**
     * 转账
     * @return array
     */
    public function send() {

        $user = Yii::$app->getUser()->getIdentity()->toArray();
        $trans = static::getDb()->beginTransaction();

        try {
            $config = static::getCommonByKey('switch_transfer_red_packet');
            if ($config == Status::COMMON_RADIO_NO) {
                throw new Exception('系统维护，暂停转账！');
            }

            $userId = $user['id'];
            if (!$userId) {
                throw new Exception('未知用户，不能转账！');
            }

            // 检查用户信息
            (new \common\models\user\User()) -> checkInfo($user);

            # 零钱封禁
            UserUnusualLog::checkUserUnusual($user['id'],Status::USER_UNUSUAL_TYPE_MONEY);

            CacheKeys::checkFrequency($userId,1);



            $money = Yii::$app->request->post('money',0);
            $payPassword = Yii::$app->request->post('pay_password','');
            $txCode = Yii::$app->request->post('tx_code','');

            $receiveId = 0;//接收ID 用户id
            if (empty($payPassword)) {
                throw new Exception('交易密码不能为空！');
            }

            if ((!Yii::$app->security->validatePassword($payPassword, $user['pay_password']))) {
                throw new Exception("交易密码不正确");
            }


            $exists = $this->redis->get(CacheKeys::IM_TRANSFER . $userId);
            if($exists){
                throw new Exception('您的速度太快了！');
            }
            $this->redis->set(CacheKeys::IM_TRANSFER . $userId, true);

            if(!$money) {
                throw new Exception('金额不能为零！');
            }

            if(!$txCode) {
                throw new Exception('接收方账号不能为空！');
            }

            if($money < 1) {
                throw new Exception('最低金额为一元钱！');
            }

            if($user['money'] < $money) {
                throw new Exception('金额不足，无法转账！');
            }

            // 检查设备码
            Common::checkDeviceCode($user);

            // 检查用户信息
            (new \common\models\user\User()) -> checkInfo($user);

            $receiveUser = User::getOneByWhere(['tx_code' => $txCode]);
            if (empty($receiveUser)) {
                throw new Exception("转账的用户不存在！");
            }
            $receiveId = $receiveUser['id'];
            // 是否好友
            $userFriendInfo = Friend::getOneByWhere([
                'user_id' => $userId,
                'friend_id' => $receiveUser['id'],
            ]);

            if (empty($userFriendInfo)) {
                throw new Exception("你和他不是好友，无法转账！");
            }


            $transInfo = $this->trans($user, $money, $receiveUser);
            if (empty($transInfo)) {
                throw new Exception("转账失败");
            }
            $imModel = new Im();
            // 发送消息
            $userMessage['message_type'] = Status::MESSAGE_TYPE_GROUP_USER_TRANSFER;
            $userMessage['type'] = Status::MESSAGE_TYPE_GROUP_USER_TRANSFER;
            $userMessage['transfer_id'] = $transInfo['id'];
            $userMessage['money'] = $transInfo['money'];
            $userMessage['tx_code'] = $user['tx_code'];
            $userMessage['user_phone'] = $user['login_name'];
//            $userMessage['user_face'] = $user['user_face'] ? static::getAvatar($user['user_face']) : '';
//            $userMessage['nick_name'] = $user['nick_name'] ?: '';
            $userMessage['receive_tx_code'] = $receiveUser['tx_code'];
//            $userMessage['receive_user_phone'] = $receiveUser['login_name'];
//            $userMessage['receive_user_face'] = $receiveUser['user_face'] ? static::getAvatar($receiveUser['user_face']) : '';
            $userMessage['receive_nick_name'] = $receiveUser['nick_name'] ?: '';
            $userMessage['time'] = date('Y-m-d H:i:s');
            $imRes = $imModel->sendUserMessage($receiveUser['tx_code'], $userMessage, $user['tx_code']);
            if (!$imRes) {
                throw new Exception("转账异常");
            }

            $trans->commit();
            return Functions::formatRestAPI(0, '转账成功');
        }  catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '服务异常');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI($e->getCode() ? $e->getCode() : 1, $e->getMessage());
        } finally {
            $this->redis->del(CacheKeys::IM_TRANSFER . $userId);
        }
    }


    // 转账操作
    public function trans(
        $userInfo = [],
        $money = 0,
        $receiveUser = []
    ) {
        if (!$userInfo || !$money || !$receiveUser) {
            return null;
        }

        // 加入转账表
        $insertData['money'] = $money;
        $insertData['user_id'] = (int) $userInfo['id'];
        $insertData['user_code'] = $userInfo['user_code'];
        $insertData['user_tx_code'] = $userInfo['tx_code'];
//        $insertData['user_face'] = $userInfo['user_face'];
//        $insertData['user_nick_name'] = $userInfo['nick_name'];
        $insertData['receive_user_id'] = (int) $receiveUser['id'];
        $insertData['receive_user_code'] = $receiveUser['user_code'];
        $insertData['receive_user_tx_code'] = $receiveUser['tx_code'];
//        $insertData['receive_user_face'] = $receiveUser['user_face'];
//        $insertData['receive_user_nick_name'] = $receiveUser['nick_name'];
        $insertData['create_time'] = date('Y-m-d H:i:s');

        $resTransferInsert = static::insertData($insertData);
        if ($resTransferInsert === false) {
            throw new Exception('系统异常，请稍后尝试！');
        }

        $insertData['id'] = (int) $resTransferInsert;

        // 拼接返回信息
        $return = $insertData;

        // 发送方 余额信息
        UserMoneyLog::record(
            $userInfo['id'],
            Status::PROP_TYPE_MONEY,
            Status::MONEY_LOG_TYPE_TRANSFER,
            -1 * $money,
            Status::MONEY_LOG_TYPE_MAP[Status::MONEY_LOG_TYPE_TRANSFER] ?? '',
            '转账',
            $resTransferInsert
        );

        // 接收方 余额信息
        UserMoneyLog::record(
            $receiveUser['id'],
            Status::PROP_TYPE_MONEY,
            Status::MONEY_LOG_TYPE_RECEIVE_TRANSFER,
            $money,
            Status::MONEY_LOG_TYPE_MAP[Status::MONEY_LOG_TYPE_RECEIVE_TRANSFER] ?? '',
            '接受转账',
            $resTransferInsert
        );
        return $return;
    }


    /**
     * 转账详情
     * @param Integer $id
     * @return array
     * state 5  -  个人红包 或者专属 但是当前用户不能领取
     * state 4  -  红包已过期
     * state 3  -  已被领取完
     * state 2  -  已领取
     * state 1  -  未领取
     */
    public function getInfo($id = 0)
    {
        try {

            $user = (new User()) -> checkUser();

            if (empty($id)) {
                throw new Exception('参数错误');
            }

            $where['id'] = $id;
            $info = static::getObjectByWhere($where)->with([
                'receiveUser' => function ($q) {
                    $q->select(['id','login_name','user_face','nick_name','tx_code','user_code']);
                },

                'user' => function ($q) {
                    $q->select(['id','login_name','user_face','nick_name','tx_code','user_code']);
                },
            ])->asArray()->one();
            if (empty($info)) {
                throw new Exception('未获取到信息');
            }

            if (($info['user_id'] != $user['id']) && ($info['receive_user_id'] != $user['id'])) {
                throw new Exception('信息有误');
            }

            $sendUserInfo = ArrayHelper::getValue($info,'user',[]);
            $receiveUserInfo = ArrayHelper::getValue($info,'receiveUser',[]);

            $data['id'] = (int) $info['id'];
            $data['money'] = $info['money'];
            $data['user_id'] = (int) $info['user_id'];
            $data['user_code'] = $info['user_code'];
            $data['user_tx_code'] = $info['user_tx_code'];
            $data['user_face'] = static::getAvatar($sendUserInfo['user_face']);
            $data['user_nick_name'] = $sendUserInfo['nick_name'];
            $data['receive_user_id'] = (int) $info['receive_user_id'];
            $data['receive_user_code'] = $info['receive_user_code'];
            $data['receive_user_tx_code'] = $info['receive_user_tx_code'];
            $data['receive_user_face'] = static::getAvatar($receiveUserInfo['user_face']);
            $data['receive_user_nick_name'] = $receiveUserInfo['nick_name'];
            $data['create_time'] = $info['create_time'];
            return Functions::formatRestAPI(0, '', $data);
        } catch(Exception $e) {
            return Functions::formatRestAPI(1,$e->getMessage());
        }
    }

}
